#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING

from sqlalchemy import BigInteger, Column, DateTime, ForeignKey, func, Integer, String, Table, Text
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.orm import backref, relationship

from backend.app.datebase.base_class import Base

if TYPE_CHECKING:
    from .user import User
    from .category import Category
    from .tag import Tag


class ArticleTag(Base):
    """ 文章标签多对多表 """
    __tablename__ = 'article_tag'
    id = Column(Integer, primary_key=True, autoincrement=True)
    article_id = Column(Integer, ForeignKey('article.id', ondelete='CASCADE'))
    tag_id = Column(Integer, ForeignKey('tag.id', ondelete='CASCADE'))


class Article(Base):
    """ 文章 """
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(128), nullable=False, comment='文章标题')
    content = Column(LONGTEXT, nullable=False, comment='文章正文')
    digest = Column(Text, comment='文章摘要')
    date_time = Column(DateTime, server_default=func.now(), comment='创建时间')
    view_num = Column(BigInteger, default=0, comment='阅读数')
    comment_num = Column(BigInteger, default=0, comment='评论数')
    picture = Column(String(256), comment='文章大头图链接')
    # 文章，作者一对一(多对一添加 uselist 强转为一对一 )
    user_id = Column(Integer, ForeignKey('user.id', ondelete='CASCADE'))
    user = relationship('User', backref=backref('article', uselist=False))
    # 文章，类型多对一
    category_id = Column(Integer, ForeignKey('category.id', ondelete='CASCADE'))
    category = relationship('Category', backref='articles')
    # 文章，标签多对多
    tags = relationship('Tag', secondary='article_tag', backref=backref('articles', lazy='dynamic'), lazy='dynamic')
